package tt.dz.service.imp.sys;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import tt.dz.dao.ext.system.OmsOperListDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.system.OmsOperList;
import tt.dz.mvc.controller.openapi.EnterpriseController;
import tt.dz.service.sys.enterpriseUserCallbackService;
import tt.dz.util.OmsConstant.ErrorCodeEnum;
import tt.dz.util.OmsConstant.MsgCodeEnum;
import tt.dz.util.OmsConstant.SuccessCodeEnum;
import tt.dz.util.StringUtil;

@Service(value = "enterpriseUserCallbackServiceImp")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class enterpriseUserCallbackServiceImp implements enterpriseUserCallbackService {
	private static Logger log = LoggerFactory
			.getLogger(EnterpriseController.class);
	@Autowired
	private OmsOperListDao operatorDaoImpl;

	/**
	 * 企业账号、回调类型（1预约、2取消预约、3充电、4取消充电）、回调参数列表{数量可变} localhost://jranl =xx&
	 * chargerid =aaa& 预约回调pojo :报文流水号、电桩地址、电桩端口号、开始预约时间。
	 * 
	 * 结束预约回调pojo :报文流水号、电桩地址、电桩端口号、结束预约时间。总金额、订单号
	 * 
	 * 开始充电回调pojo :报文流水号、电桩地址、电桩端口号、开始充电时间。
	 * 
	 * 结束充电回调pojo :报文流水号、电桩地址、电桩端口号、结束充电时间。
	 * 
	 * 账单回调pojo：预约流水号、充电流水号、电桩地址、电桩端口号、总金额、订单号
	 * 预约流水号、充电流水号是有关联的，通过充电流水号查询不到预约流水号时，预约流水号可为空。
	 */
	@Override
	public JsonCommon<?> notifyUrlCallback(String account, int callbackType,
			String... args) {
		JsonCommon json = new JsonCommon();
		// user_type=2 为企业用户
		OmsOperList omsOperList = operatorDaoImpl.findOneExampleByCondition(
				new OmsOperList(), "where account='" + account
						+ "' and user_type='2'");
		if (null == omsOperList) {
			return new JsonCommon<String>(
					ErrorCodeEnum.QueryEnterpriseUserNull.value(),
					ErrorCodeEnum.QueryEnterpriseUserNull.desc());
		}
		String result="";
		switch (callbackType) {
		case 1:// 预约回调pojo :报文流水号、电桩地址、电桩端口号、开始预约时间。
			String[] str=args;
			if(str.length!=4){
				return new JsonCommon<String>(
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgCode(),
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgInfo());
			}
			String notifyUrl = omsOperList.getNotify_url();
			String finalurl = notifyUrl + "?oms_msg_bespeak_jrnl=" + args[0]
					+ "&charger_id=" + args[1] + "&port_no=" + args[2]
					+ "&start_time=" + args[3];
			result=urlConnction(finalurl);
				if (StringUtil.isNotBlank(result)) {
					json.setPojo(result);
					json.setCode(SuccessCodeEnum.SuccessCode.value());
					json.setMsg(SuccessCodeEnum.SuccessCode.desc());
				} else {
					json.setCode(ErrorCodeEnum.ParamValueError.value());
					json.setMsg(ErrorCodeEnum.ParamValueError.desc());
				}
			break;
		case 2:// 结束预约回调pojo :报文流水号、电桩地址、电桩端口号、结束预约时间。总金额、订单号
			String[] str1=args;
			if(str1.length!=6){
				return new JsonCommon<String>(
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgCode(),
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgInfo());
			}
			String notifyUrl1 = omsOperList.getNotify_url();
			String finalurl1 = notifyUrl1 + "?oms_msg_bespeak_jrnl=" + args[0]
					+ "&charger_id=" + args[1] + "&port_no=" + args[2]
					+ "&actual_end_time=" + args[3] + "&bespeak_deal_charge="
					+ args[4] + "&order_no=" + args[5];
			result=urlConnction(finalurl1);
			if (StringUtil.isNotBlank(result)) {
				json.setPojo(result);
				json.setCode(SuccessCodeEnum.SuccessCode.value());
				json.setMsg(SuccessCodeEnum.SuccessCode.desc());
			} else {
				json.setCode(ErrorCodeEnum.ParamValueError.value());
				json.setMsg(ErrorCodeEnum.ParamValueError.desc());
			}
			break;
		case 3:// 开始充电回调pojo :报文流水号、电桩地址、电桩端口号、开始充电时间。
			String[] str2=args;
			if(str2.length!=4){
				return new JsonCommon<String>(
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgCode(),
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgInfo());
			}
			String notifyUrl2 = omsOperList.getNotify_url();
			String finalurl2 = notifyUrl2 + "?oms_msg_bespeak_jrnl=" + args[0]
					+ "&charger_id=" + args[1] + "&port_no=" + args[2]
					+ "&start_time=" + args[3];
			result=urlConnction(finalurl2);
			if (StringUtil.isNotBlank(result)) {
				json.setPojo(result);
				json.setCode(SuccessCodeEnum.SuccessCode.value());
				json.setMsg(SuccessCodeEnum.SuccessCode.desc());
			} else {
				json.setCode(ErrorCodeEnum.ParamValueError.value());
				json.setMsg(ErrorCodeEnum.ParamValueError.desc());
			}

			break;
		case 4:// 结束充电回调pojo :报文流水号、电桩地址、电桩端口号、结束充电时间。
			String[] str3=args;
			if(str3.length!=4){
				return new JsonCommon<String>(
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgCode(),
						MsgCodeEnum.REQUEST_PARAM_MISS_ERROR.getMsgInfo());
			}
			String notifyUrl3 = omsOperList.getNotify_url();
			String finalurl3 = notifyUrl3 + "?oms_msg_bespeak_jrnl=" + args[0]
					+ "&charger_id=" + args[1] + "&port_no=" + args[2]
					+ "&end_time=" + args[3];
			result=urlConnction(finalurl3);
			if (StringUtil.isNotBlank(result)) {
				json.setPojo(result);
				json.setCode(SuccessCodeEnum.SuccessCode.value());
				json.setMsg(SuccessCodeEnum.SuccessCode.desc());
			} else {
				json.setCode(ErrorCodeEnum.ParamValueError.value());
				json.setMsg(ErrorCodeEnum.ParamValueError.desc());
			}
			break;
		default:
			json.setCode(MsgCodeEnum.ERROR400.getMsgCode());
			json.setCode(MsgCodeEnum.ERROR400.getMsgInfo());
			break;
		}

		return json;
	}

	public String urlConnction(String finalurl){
		URL url;
		String result = "";
		BufferedReader in = null;
		try {
			url = new URL(finalurl);
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.connect();
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			conn.disconnect();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			log.error("error in wapaction,and e is " + e.getMessage());
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
}
